<template>
    <div class="createOrder">
        <div class="formArea">
            <el-form :model="createForm" :rules="rules" ref="createForm" label-width="80px" size="mini"
                :hide-required-asterisk="true">
                <el-form-item label="工单编号">
                    <el-input v-model="createForm.code" placeholder="请输入,忽略将自动生成" :maxlength='120'></el-input>
                </el-form-item>
                <el-form-item prop="productId">
                    <template slot='label'>
                        <span style="color: red">*</span>
                        产品
                    </template>
                    <search-input :url="'/base/p_other'" :placeholder="'查找或添加新产品'" :prop="'productId'"
                        @handleChange='handleChange' ref="product" :id="createForm.productId"
                        @clickHandle="clickHandle">
                        <el-button type="text" icon="el-icon-circle-plus-outline" style="padding:10px 0 10px 20px"
                            @click="openDialog({refName:'addNewProduct'})">
                            添加新产品
                        </el-button>
                    </search-input>
                </el-form-item>
                <el-form-item style='margin-bottom:8px' v-show='createForm.productId'>
                    <div class="productDisplay__e5bCl">
                        <div class="productDisplayItem__gvh_D">
                            <div class="productDisplayItemLabel__95jJE">产品编号</div>
                            <div class="productDisplayItemValue__I8W5_">{{productInfo.code}}</div>
                        </div>
                        <div class="productDisplayItem__gvh_D">
                            <div class="productDisplayItemLabel__95jJE">产品名称</div>
                            <div class="productDisplayItemValue__I8W5_">{{productInfo.name}}</div>
                        </div>
                        <div class="productDisplayItem__gvh_D">
                            <div class="productDisplayItemLabel__95jJE">产品规格</div>
                            <div class="productDisplayItemValue__I8W5_">{{productInfo.specification}}</div>
                        </div>
                    </div>
                </el-form-item>
                <el-form-item prop="planedNumber">
                    <template slot='label'>
                        <span style="color: red">*</span>
                        计划数
                    </template>
                    <el-input-number v-model="createForm.planedNumber" controls-position="right" :min="0"
                        placeholder="请填写" @change="planNumChange">
                    </el-input-number>
                </el-form-item>
                <el-form-item prop="planTime">
                    <template slot='label'>
                        <span style="color: red">*</span>
                        计划时间
                    </template>
                    <el-date-picker v-model="createForm.planTime" type="datetimerange" range-separator="至"
                        start-placeholder="开始日期" end-placeholder="结束日期" format="yyyy-MM-dd HH:mm"
                        @change='planTimeChange' :clearable='false' :default-time="['00:00:00', '23:59:59']">
                    </el-date-picker>
                </el-form-item>
                <el-form-item label="关联单据">
                    <span style='color:#409EFF;cursor:pointer' @click='skipSales'>
                        {{$route.query.salesCode || '-'}}
                    </span>
                </el-form-item>
                <el-form-item label="状态">
                    未开始
                </el-form-item>
                <el-form-item label="备注">
                    <el-input type="textarea" v-model="createForm.comment"></el-input>
                </el-form-item>

                <!-- ====================自定义==================== -->
                <el-form-item v-for='(item, i) in customFiledList' :key="i" :label='item.chineseName' :prop="item.id"
                    v-show='hiddenRule(item)'>
                    <el-checkbox-group v-show="false" v-model="createForm[item.id]"></el-checkbox-group>
                    <template slot='label'>
                        <span style="color: red" v-show="requireRsterisk(item)">*</span>
                        {{ item.chineseName }}
                        <el-tooltip class="item" effect="dark" :content="item.tips" placement="top" v-show='item.tips'>
                            <span class="iconfont icon-wenhao wenhao"></span>
                        </el-tooltip>
                    </template>
                    <formLibrary :formItem='item' @formItemHandle='formItemHandle' :defaultData="defaultData"
                        @uploadProgress='uploadProgress' ref='formLibrary'>
                    </formLibrary>
                </el-form-item>
            </el-form>
        </div>

        <div class="productTask">
            <div class="operate clearfix">
                <span>生产任务</span>
                <div class="operate_btn">
                    <el-button type="text" size="mini" icon="el-icon-plus" @click="openDialog({refName:'procedureAdd'})">从工序中添加
                    </el-button>
                    <el-button type="text" size="mini" icon="el-icon-plus" @click="openDialog({refName:'boardAdd'})">从模版中添加
                    </el-button>
                    <el-button type="text" size="mini" @click="openDialog({refName:'saveBoard'})">保存为模版</el-button>
                </div>
            </div>
            <el-table :data="productTable" border style="width: 100%" max-height="420"
                :header-cell-style="{background:'#fafafa',color:'#000',fontWeight:400,fontSize:'12px'}"
                :cell-style="{color:'#5a5a5a',fontSize:'12px',fontWeight:400}" row-key='mockId'>
                <el-table-column prop="xh" label="序号">
                    <template scope="scope">
                        <span>{{scope.$index + 1}}</span>
                    </template>
                </el-table-column>
                <el-table-column prop="processName" label="工序名称" width="150" show-overflow-tooltip>
                </el-table-column>
                <el-table-column prop="processCode" label="工序编号" width="150" show-overflow-tooltip>
                </el-table-column>
                <el-table-column prop="permissionsName" label="报工权限" width="130" show-overflow-tooltip>
                </el-table-column>
                <el-table-column prop="rate" label="报工数配比" width="100" show-overflow-tooltip>
                </el-table-column>
                <el-table-column prop="planedNumber" label="计划数" width="100" show-overflow-tooltip>
                </el-table-column>
                <el-table-column prop="goodProductNumber" label="良品数">
                </el-table-column>
                <el-table-column prop="badProductNumber" label="不良品数">
                </el-table-column>
                <el-table-column prop="badProductList" label="不良品项列表" width="110" show-overflow-tooltip>
                </el-table-column>
                <el-table-column prop="planedStartTime" label="计划开始时间" width="150">
                </el-table-column>
                <el-table-column prop="planedEndTime" label="计划结束时间" width="150">
                </el-table-column>
                <el-table-column prop="actualStartTime" label="实际开始时间" width="150">
                </el-table-column>
                <el-table-column prop="actualEndTime" label="实际结束时间" width="150">
                </el-table-column>
                <el-table-column fixed="right" label="操作" width="150">
                    <template slot-scope="scope">
                        <el-button type="text" size="small" @click="openDialog({refName:'editProcess',row:scope.row,index:scope.$index})">编辑
                        </el-button>
                        <el-popconfirm placement='top' confirm-button-text='删除' title="确认删除工序？"
                            @confirm='confirmDel(scope.$index)'>
                            <el-button slot="reference" type="text" size="small" style="margin-left:10px">删除</el-button>
                        </el-popconfirm>
                    </template>
                </el-table-column>
                <div slot="empty">
                    <el-empty :image-size="100"></el-empty>
                </div>
            </el-table>

            <div class="btn">
                <el-button type="primary" plain size="small" @click="handleCancel">取消
                </el-button>
                <el-button type="primary" size="small" @click="save">保存</el-button>
            </div>
        </div>

        <!-- 添加新产品 -->
        <add-product ref='addNewProduct' @emitAddProduct='emitAddProduct'></add-product>

        <!-- 编辑工序 -->
        <edit-process ref='editProcess' :planedNumber='createForm.planedNumber' @emitEditProcess='emitEditProcess' :planTime='createForm.planTime'></edit-process>

        <!-- 从工序中添加 -->
        <add-from-process ref='procedureAdd' :planTime='createForm.planTime' @emitAddProcess='emitAddProcess'
            :planedNumber='createForm.planedNumber'></add-from-process>

        <!-- 从模版中添加 -->
        <add-from-board ref='boardAdd' @emitAddFromBoard='emitAddFromBoard'></add-from-board>

        <!-- 保存为模版 -->
        <save-board ref="saveBoard" @emitSaveBoard='emitSaveBoard'></save-board>
    </div>
</template>

<script>
    import {
        processRouteHandle
    } from '@/api/baseController'
    import {
        fromModel,
        workOrderHandle,
        woDetail
    } from '@/api/produceController'
    import {
        loginUserMess
    } from '@/api/loginController'
    import {
        customFieldOther,
        fillFieldMess
    } from '@/api/customFieldController'
    import Sortable from "sortablejs"
    import searchInput from './searchInput.vue'
    import formLibrary from '@/components/formLibrary'
    import addProduct from './operationMode/addProduct.vue'
    import addFromProcess from './operationMode/addFromProcess.vue'
    import editProcess from './operationMode/editProcess.vue'
    import addFromBoard from './operationMode/addFromBoard.vue'
    import saveBoard from './operationMode/saveBoard.vue'
    export default {
        data() {
            var planedNumber = (rule, value, callback) => {
                let tempValue = ''
                let index = String(value).indexOf('.')
                tempValue = index != -1 ? String(value).slice(0, index) : String(value)
                if (value == undefined) {
                    return callback(new Error('请输入计划数'));
                } else if (Number(value) == 0) {
                    return callback(new Error('计划数必须大于0'))
                } else if (tempValue.length > 10) {
                    return callback(new Error('整数位最多支持10位数字'));
                } else if (!(/^[0-9]+(.[0-9]{1,6})?$/.test(value))) {
                    return callback(new Error('小数点后最多保留6位数字'));
                } else {
                    callback()
                }
            };
            return {
                createForm: {
                    code: '',
                    productId: '',
                    planedNumber: undefined,
                    startTime: '',
                    endTime: '',
                    comment: '',
                    planTime: [new Date().dateFormat('yyyy-MM-dd 00:00'), new Date().dateFormat('yyyy-MM-dd 23:59')],
                    isUrgent:0
                },
                rules: {
                    productId: [{
                        required: true,
                        message: '请选择产品',
                    }],
                    planedNumber: [{
                        required: true,
                        validator: planedNumber,
                        trigger: 'blur'
                    }],
                    planTime: [{
                        required: true,
                        message: '请输入计划时间',
                    }],
                },
                productTable: [],
                index: 0,
                customFiledList: [],
                defaultData: [], // 自定义字段值
                customFiledData: [],
                customState: true, // 判断单选/复选 选值是否正确
                customErrorLabel: '', // 选值错误提示语
                // 关联属性信息
                relevanceProp: [],
                productInfo: {},
                userMess: {},
                uploadFlag: true
            }
        },
        components: {
            searchInput,
            formLibrary,
            addProduct,
            addFromProcess,
            editProcess,
            addFromBoard,
            saveBoard
        },
        watch: {
            createForm: {
                handler() {
                    this.hiddenRule('')
                },
                deep: true,
            }
        },
        mounted() {
            this.getWoDetail({id:this.$route.query.id})
            // 阻止默认行为
            document.body.ondrop = function (e) {
                e.preventDefault()
                e.stopPropagation()
            };
            this.rowDrop();
        },
        methods: {
            // 自定义字段
            getCustomFieldOther() {
                customFieldOther({
                    type: 'workOrder'
                }).then(res => {
                    this.customFiledList = []
                    this.relevanceProp = []
                    if (res.code == 200) {
                        // 自定义字段数据
                        res.data.map(item => {
                            item.customFieldMess.objectsValue = item.objectsValue
                            this.customFiledList.push(item.customFieldMess)
                        })
                        // 添加自定义字段的校验规则(是否必填)
                        this.customFiledList.map(item => {
                            let r = item.hidden
                            item.hidden = r.replace(/\${工单./g, 'formItemData["').replace(/\}/g, '"]')
                                .replace(/\${用户信息./g, 'userFormItemData["')
                            item.id = item.id + ''
                            let obj = {}
                            if (JSON.parse(item.fieldAttribute).required && item.fieldType != 'inputNumber') {
                                obj[item.id] = [{
                                    required: true,
                                    message: item.chineseName + '不能为空'
                                }]
                            }else if(item.fieldType == 'inputNumber'){
                                const numberRule = (rule, v, callback) => {
                                    let tempValue = ''
                                    let index = String(this.createForm[item.id]).indexOf('.')
                                    tempValue = index != -1 ? String(this.createForm[item.id]).slice(0,index) : String(this.createForm[item.id])
                                    if (!this.createForm[item.id] && item.isRequired) {
                                        return callback(new Error(`${item.chineseName}不能为空！`));
                                    }else if(tempValue.length > 10){
                                        return callback(new Error('整数位最多支持10位数字'));
                                    }else if(this.createForm[item.id] != undefined && !(/^[0-9]+(.[0-9]{1,6})?$/.test(this.createForm[item.id]))){
                                        return callback(new Error('小数点后最多保留6位数字'));
                                    }else {
                                        callback()
                                    }
                                }
                                obj[item.id] = [{
                                    validator: numberRule,
                                    trigger:'blur'
                                }]
                            }
                            this.rules = Object.assign(this.rules, obj)
                            if (item.fieldType == 'relevanceProp') {
                                this.relevanceProp.push({
                                    id: item.id,
                                    objectFieldId: item.objectFieldId,
                                    type: item.correlationField
                                })
                            }
                        })
                        this.getLoginUserMess()
                    }
                })
            },
            // 用户信息
            getLoginUserMess(data) {
                loginUserMess(data).then(res => {
                    this.loading = false
                    if (res.code == 200) {
                        this.userMess = res.data
                    }
                })
            },
            // 关联对象-字段信息
            getFillFieldMess(data, fillRule, n) {
                fillFieldMess(data).then(res => {
                    this.defaultData = []
                    for (let key in this.createForm) {
                        if (Number(key)) {
                            this.defaultData.push({
                                customFieldId: key,
                                value: this.createForm[key]
                            })
                        }
                    }
                    if (res.code == 200) {
                        // 如果该条数据有自定义字段
                        if (res.data.customFieldVos != null) {
                            /* 
                                遍历关联对象的填充规则
                                遍历该条数据的自定义字段列表
                                将填充规则中的来源值(from) 赋给 指定控件(to)
                            */
                            fillRule.map(item => {
                                let dataArr = []
                                let f = res.data.customFieldVos.find(res => {
                                    return res.customFieldId == item.from
                                })
                                if (f != undefined) {
                                    res.data.customFieldVos.map(k => {
                                        if (k.customFieldId == item.from) {
                                            this.createForm[item.to] = k.value
                                            this.defaultData = this.defaultData.filter(j => j
                                                .customFieldId != item.to)
                                            this.defaultData.push({
                                                customFieldId: item.to,
                                                value: k.value
                                            })
                                        }
                                    })
                                } else {
                                    this.createForm[item.to] = ''
                                    this.defaultData.map(k => {
                                        if (k.customFieldId == item.to) {
                                            let d = this.customFiledList.find(res => {
                                                return res.id == item.to
                                            })
                                            if (d.fieldType == 'picture' || d.fieldType ==
                                                'upload' || d.fieldType == 'selectChecked') {
                                                dataArr.push({
                                                    customFieldId: k.customFieldId,
                                                    value: "[]"
                                                })
                                            } else {
                                                dataArr.push({
                                                    customFieldId: k.customFieldId,
                                                    value: ""
                                                })
                                            }
                                        } else {
                                            dataArr.push({
                                                customFieldId: k.customFieldId,
                                                value: k.value
                                            })
                                        }
                                    })
                                    this.defaultData = dataArr
                                }
                            })
                        } else {
                            fillRule.map(item => {
                                let dataArr = []
                                this.createForm[item.to] = ''
                                this.defaultData.map(k => {
                                    if (k.customFieldId == item.to) {
                                        let d = this.customFiledList.find(res => {
                                            return res.id == item.to
                                        })
                                        if (d.fieldType == 'picture' || d.fieldType ==
                                            'upload' || d.fieldType == 'selectChecked') {
                                            dataArr.push({
                                                customFieldId: k.customFieldId,
                                                value: "[]"
                                            })
                                        } else {
                                            dataArr.push({
                                                customFieldId: k.customFieldId,
                                                value: ""
                                            })
                                        }
                                    } else {
                                        dataArr.push({
                                            customFieldId: k.customFieldId,
                                            value: k.value
                                        })
                                    }
                                })
                                this.defaultData = dataArr
                            })
                        }
                        // 关联属性赋值
                        this.relevanceProp.map(item => {
                            if (item.objectFieldId == n) {
                                this.createForm[item.id] = res.data[item.type]
                                this.defaultData = this.defaultData.filter(j => j.customFieldId != item
                                    .id)
                                this.defaultData.push({
                                    customFieldId: item.id,
                                    value: res.data[item.type]
                                })
                            }
                        })
                    }
                })
            },
            // 自定义表单项数据--表单子组件传递的值
            formItemHandle(d) {
                // 子组件的值赋给表单
                this.$set(this.createForm, d.name, d.value)
                // 操作的是关联对象
                if (d.relevanceObject != undefined) {
                    if (d.relevanceObject.id) {
                        let data = {
                            id: d.relevanceObject.id,
                            type: d.relevanceObject.businessObject
                        }
                        this.getFillFieldMess(data, d.relevanceObject.fillRule, d.name)
                    } else {
                        this.customFiledList.map(item => {
                            if (item.objectFieldId == d.name) {
                                this.createForm[item.id] = ''
                                this.defaultData.map(k => {
                                    if (k.customFieldId == item.id || k.customFieldId == d.name) {
                                        k.value = ''
                                    }
                                })
                            }
                        })
                        for (let key in this.createForm) {
                            let ind = this.defaultData.findIndex(res => {
                                return res.customFieldId == key
                            })
                            if (ind != -1) {
                                this.$set(this.defaultData, ind, {
                                    customFieldId: key,
                                    value: this.createForm[key]
                                })
                            } else {
                                this.defaultData.push({
                                    customFieldId: key,
                                    value: this.createForm[key]
                                })
                            }
                        }
                    }
                }
            },
            // 自定义隐藏设置--隐藏条件触发
            hiddenRule(d) {
                let formItemData = {
                    '工单编号': this.createForm.code,
                    '产品编号': this.productInfo.code,
                    '产品名称': this.productInfo.name,
                    '产品规格': this.productInfo.specification,
                    '计划数': this.createForm.planedNumber,
                    '工单状态': '未开始',
                    '计划开始时间': this.utils.formatTime(this.createForm.planTime[0],
                        'yyyy-MM-dd hh:mm:ss'),
                    '计划结束时间': this.utils.formatTime(this.createForm.planTime[1],
                        'yyyy-MM-dd hh:mm:ss')
                }
                let userFormItemData = {
                    '账号': this.userMess.account,
                    '姓名': this.userMess.name,
                    '手机号': this.userMess.mobile,
                    '角色': this.userMess.role,
                }
                this.customFiledList.map(item => {
                    if (formItemData[item.chineseName] == undefined) {
                        if (this.createForm[item.id] != undefined) {
                            formItemData[item.chineseName] = this.createForm[item.id]
                        } else {
                            formItemData[item.chineseName] = ''
                        }
                    }
                    if (userFormItemData[item.chineseName] == undefined) {
                        if (this.createForm[item.id] != undefined) {
                            userFormItemData[item.chineseName] = this.createForm[item.id]
                        } else {
                            userFormItemData[item.chineseName] = ''
                        }
                    }
                })
                let state = null
                try {
                    state = !eval(d.hidden)
                } catch {
                    state = true
                }
                //必填项字段若是被隐藏不校验
                if (this.rules[d.id]) {
                    if(d.fieldType == 'inputNumber'){
                        if(JSON.parse(d.fieldAttribute).required){ //inputNumber 必填 && 切换触发隐藏条件
                            d.isRequired = state
                        }
                    }else{
                        this.rules[d.id][0].required = state
                    }
                }
                return state
            },
            requireRsterisk(d) {
                if (this.rules[d.id]) {
                    if(d.fieldType == 'inputNumber'){
                        return JSON.parse(d.fieldAttribute).required || false
                    }else{
                        return this.rules[d.id][0].required || false
                    }
                }
            },
            customData(v, data) {
                if (Number(v)) {
                    let id = ''
                    data.map(item => {
                        if (item.value == v) {
                            id = item.label
                        }
                    })
                    return id
                } else {
                    return v
                }
            },
            // 附件/图片上传是否完成
            uploadProgress(s) {
                this.uploadFlag = s
            },

            //工单详情
            getWoDetail(data) {
                woDetail(data).then(res => {
                    if (res.code == 200) {
                        this.createForm.code = res.data.workOrderCode
                        this.createForm.productId = res.data.productId
                        this.$refs.product.getDataList({name:''})
                        this.createForm.planedNumber = res.data.planedNumber
                        this.createForm.comment = res.data.comment
                        this.createForm.planTime = [res.data.planedStartTime,res.data.planedEndTime]
                        this.productTable = res.data.missionList
                        this.createForm.state = this.$route.query.state
                        this.productInfo = {
                            code: res.data.productCode,
                            name: res.data.productName,
                            specification: res.data.productSpecification
                        }
                        this.defaultData = []
                        this.getCustomFieldOther()
                        // 不为null说明该条数据有自定义字段，将自定义字段值初始化给表单
                        if(res.data.customFieldVos != null) {
                            res.data.customFieldVos.map(item => {
                               this.$set(this.createForm, item.customFieldId, item.value)
                               this.defaultData.push({
                                   customFieldId: item.customFieldId,
                                   value: item.value
                               })
                            })
                        }
                        this.productTable.forEach((i,index) => {
                            const {formatTime} = this.utils
                            i.mockId = index + '_' + i.id
                            i.actualStartTime = formatTime(i.actualStartTime,'yyyy-MM-dd hh:mm') || '-'
                            i.actualEndTime = formatTime(i.actualEndTime,'yyyy-MM-dd hh:mm') || '-'
                            i.planedStartTime = formatTime(i.planedStartTime,'yyyy-MM-dd hh:mm')
                            i.planedEndTime = formatTime(i.planedEndTime,'yyyy-MM-dd hh:mm')
                        })
                    }
                })
            },

            //添加新产品--添加新产品弹框关闭
            emitAddProduct(productId){
                this.$refs.product.getDataList({
                    name: ''
                })
                this.createForm.productId = productId
            },

            //添加工序
            emitAddProcess(processData){
                this.productTable = [...this.productTable, ...processData]
                this.productTable.forEach((i,index) => i.mockId = index + '_' + i.id)
            },

            //编辑工序
            emitEditProcess(processData,index){
                const {formatTime} = this.utils
                const {rate,planedNumber,planedTime,customFieldVos} = processData
                this.productTable[index].rate = rate
                this.productTable[index].planedNumber = planedNumber
                this.productTable[index].planedStartTime = formatTime(planedTime[0],'yyyy-MM-dd hh:mm')
                this.productTable[index].planedEndTime = formatTime(planedTime[1],'yyyy-MM-dd hh:mm')
                this.productTable[index].customFieldVos = customFieldVos
            },

            //从模板中添加
            emitAddFromBoard(id){
                this.getFromModel({id}, {flag: true})
            },

            //保存为模板
            emitSaveBoard(form){
                if (!this.productTable.length) {
                    this.utils.showMsg('请先添加工序', 'error')
                    return
                }
                let data = {
                    ...form,
                    list: []
                }
                data.list = this.productTable.map((i,index) => {
                    return {
                        code: i.processCode,
                        id: i.id,
                        name: i.processName,
                        order: index + 1,
                        rate: i.rate,
                        type: '工序',
                    }
                })
                this.getProcessRouteHandle(data)
            },

            //添加新产品--单位
            clickHandle(name, prop) {
                if (prop == 'productId') {
                    this.openDialog({refName:'addNewProduct',query:name})
                }
            },

            //工单操作
            getWorkOrderHandle(data) {
                workOrderHandle(data).then(res => {
                    if (res.code == 200) {
                        this.$router.push('/productionManagement/workOrder')
                        this.utils.showMsg("工单创建成功", 'success')
                    }
                })
            },

            //保存为模版
            getProcessRouteHandle(data) {
                processRouteHandle(data).then(res => {
                    if (res.code == 200) {
                        this.utils.showMsg('模版保存成功', 'success')
                    }
                })
            },

            //删除
            confirmDel(index) {
                this.productTable.splice(index, 1)
                this.utils.showMsg('删除成功', 'success')
            },

            //从模版中添加
            getFromModel(data, flag) {
                fromModel(data, flag).then(res => {
                    if (res.code == 200) {
                        const {formatTime} = this.utils
                        res.data.forEach(e => {
                            e.planedNumber = this.createForm.planedNumber == undefined ? 0 : this
                                .createForm.planedNumber * e.rate
                            e.goodProductNumber = '-'
                            e.badProductNumber = '-'
                            e.actualStartTime = '-'
                            e.actualEndTime = '-'
                            e.planedStartTime = formatTime(e.planedStartTime,'yyyy-MM-dd hh:mm')
                            e.planedEndTime = formatTime(e.planedEndTime,'yyyy-MM-dd hh:mm')
                        })
                        //添加或者直接覆盖
                        this.productTable = flag.flag ? [...this.productTable, ...res.data] : res.data
                        this.productTable.forEach((i,index) => i.mockId = index + '_' + i.id)
                    }
                })
            },
            openDialog(payload){
                this.$refs[payload.refName].add(payload)
                if(payload.refName == 'addNewProduct') this.$refs.product.blur()
            },

            //计划数改变
            planNumChange(n) {
                if(n == undefined) return
                //计划数改变 工序计划书随之改变 -- 可能会小数点超过6位 在点击编辑直接会触发表单验证
                let reg = new RegExp(`^\\d+(\\.\\d{1,6})?$`)
                if (this.productTable.length) {
                    this.productTable.forEach(i => {
                        i.planedNumber = !reg.test(n * i.rate) ? (n * i.rate).toFixed(6) : n * i.rate
                    })
                }
            },

            //计划开始时间变化
            planTimeChange(n) {
                const {formatTime} = this.utils
                this.productTable.length && this.productTable.forEach(i => {
                    i.planedStartTime = formatTime(n[0],'yyyy-MM-dd hh:mm')
                    i.planedEndTime = formatTime(n[1],'yyyy-MM-dd hh:mm')
                })
            },

            //行拖拽
            rowDrop() {
                const tbody = document.querySelector(".el-table__body-wrapper tbody")
                const _this = this
                Sortable.create(tbody, {
                    animation: 150,
                    onEnd({
                        newIndex,
                        oldIndex
                    }) {
                        const currRow = _this.productTable.splice(oldIndex, 1)[0]
                        _this.productTable.splice(newIndex, 0, currRow)
                    }
                })
            },

            //searchinput变化时
            handleChange(v) {
                this.createForm.productId = v.v
                this.productInfo = v.productInfo
                this.getFromModel({productId: v.v}, {flag: false})
            },

            //销售订单详情
            skipSales(){
                this.$router.push({
                    path: '/productionManagement/salesOrder/edit',
                    query: {
                        id:this.$route.query.salesId
                    }
                })
            },

            //保存
            save() {
                this.$refs.createForm.validate((valid) => {
                    if (valid) {
                        if (!this.productTable.length) {
                            this.utils.showMsg('请添加工艺路线', 'success')
                        } else {
                            const {formatTime} = this.utils
                            let data = {
                                customFieldVos:[],
                                process:[]
                            }
                            let JSONForm = JSON.parse(JSON.stringify(this.createForm))
                            for (const key in JSONForm) {
                                if ((!isNaN(parseFloat(key)) && isFinite(key))) {
                                    delete JSONForm[key]
                                }else if(key != 'planTime'){
                                    data[key] = JSONForm[key]
                                    data.startTime = formatTime(this.createForm.planTime[0],'yyyy-MM-dd hh:mm:00')
                                    data.endTime = formatTime(this.createForm.planTime[1],'yyyy-MM-dd hh:mm:59')
                                    data.code = data.code == this.$route.query.code ? '' : data.code
                                }
                            }
                            data.process = this.productTable.map((i,index) => {
                                return {
                                    id: i.id,
                                    order: index + 1,
                                    startTime: formatTime(i.planedStartTime,'yyyy-MM-dd hh:mm:00'),
                                    endTime: formatTime(i.planedEndTime,'yyyy-MM-dd hh:mm:59'),
                                    rate: i.rate,
                                    planedNumber: i.planedNumber,
                                    customFieldVos:i.customFieldVos
                                }
                            })
                            data.process[data.process.length - 1].order = 0 //最后一道工序order为0
                            for (let key in this.createForm) {
                                if (Number(key)) {
                                    this.customFiledList.forEach(item => {
                                        if (
                                            item.id == key && this.createForm[key] != null 
                                                && String(this.createForm[key]).length
                                        ) {
                                            data.customFieldVos.push({
                                                customFieldId: item.id,
                                                value: this.createForm[key]
                                            })
                                        }
                                    })
                                }
                            }
                            // 关联对象后，判断单选框/复选框关联过来的值是否存在
                            this.customState = true
                            this.customErrorLabel = ''
                            this.customFiledList.map(item => {
                                // 单选框
                                if (item.fieldType == 'selectRadio') {
                                    if (this.createForm[item.id] != '' && this.createForm[item.id] !=
                                        undefined) {
                                        let s = JSON.parse(item.checkBox).find(res => {
                                            return this.createForm[item.id] == res.value
                                        })
                                        if (s == undefined) {
                                            this.customState = false
                                            this.customErrorLabel = '【' + item.chineseName + '】选项值不正确'
                                        }
                                    }
                                }
                                // 复选框
                                if (item.fieldType == 'selectChecked') {
                                    if (this.createForm[item.id] != '' && this.createForm[item.id] !=
                                        undefined && this.createForm[item.id] != '[]') {
                                        JSON.parse(this.createForm[item.id]).map(k => {
                                            let s = JSON.parse(item.checkBox).find(res => {
                                                return res.value == k
                                            })
                                            if (s == undefined) {
                                                this.customState = false
                                                this.customErrorLabel = '【' + item.chineseName +
                                                    '】选项值不正确'
                                            }
                                        })
                                    }
                                }
                            })
                            if (this.customState) {
                                if (this.uploadFlag) {
                                    this.$refs.formLibrary != undefined && this.$refs.formLibrary.map(k => {
                                        k.removeData('ok')
                                    })
                                    this.getWorkOrderHandle(data)
                                } else {
                                    this.utils.showMsg('正在上传，请稍后', 'warning')
                                }
                            } else {
                                this.utils.showMsg(this.customErrorLabel, 'error')
                            }
                        }
                    } else {
                        return false;
                    }
                });
            },
            // 取消
            handleCancel() {
                this.$refs.formLibrary != undefined && this.$refs.formLibrary.map(k => {
                    k.removeData('cancle')
                })
                this.$router.push('/productionManagement/workOrder')
            },
        },
    }
</script>

<style lang="less" scoped>
    .createOrder {
        overflow: auto;

        .formArea {
            width: 420px;
            padding: 40px 0px 0px 60px;
        }

        .productTask {
            margin: 60px 40px 0px;

            .operate {
                span {
                    font-size: 12px;
                    float: left;
                }

                .operate_btn {
                    float: right;
                }

                margin-bottom: 10px;
            }

            .btn {
                margin: 26px 0;
                text-align: center;

                /deep/ .el-button--primary span {
                    margin-left: 0;
                }

                /deep/ .el-button--primary {
                    padding: 7px 35px;
                }
            }
        }

        .dialogBody {
            padding: 20px 100px;
            background-color: #fbfbfb;

            /deep/ .el-form-item:last-child {
                margin-bottom: 0;
            }

            .el-select {
                /deep/ .el-input__suffix-inner {
                    display: none;
                }

                /deep/ .el-tag.el-tag--info .el-tag__close {
                    display: none;
                }
            }
        }

        .title {
            color: rgba(0, 0, 0, .85);
            font-size: 14px;
            font-weight: 500;
        }

        /deep/ .el-select {
            width: 100%;
        }

        /deep/ .el-input-number--mini {
            width: 100%;
        }

        /deep/ .el-autocomplete {
            width: 100%;
        }

        /deep/ .el-range-editor--mini.el-input__inner {
            width: 100%;
        }

        /deep/ .el-table__empty-text {
            .el-empty {
                padding: 0;
            }
        }

        /deep/ .el-empty__image {
            height: 60px;
        }

        /deep/ .el-empty__image svg {
            vertical-align: text-top;
        }

        /deep/ .el-empty__description {
            margin-top: 10px;
        }

        /deep/ .el-date-editor.el-input,
        .el-date-editor.el-input__inner {
            width: 100%;
        }

        /deep/ .el-range-editor.el-input__inner {
            width: 100%;
        }

        /deep/ .el-range-editor .el-range-input {
            flex: 7;
        }

        /deep/ .el-date-editor .el-range-separator {
            flex: 1;
        }

        /deep/ .el-input-group__append {
            background-color: #409EFF;
            color: white;
        }
    }
</style>